const { ipcRenderer } = require('electron');
const path = require('path');
const os = require('os');

class ServerToServerTransferApp {
    constructor() {
        this.server1Connection = null;
        this.server2Connection = null;
        this.server1Path = '/home/orangepi';
        this.server2Path = '/home';
        this.selectedFiles = new Map(); // panelId -> Set of files
        
        this.initializeElements();
        this.bindEvents();
        this.updateServerList();
    }

    initializeElements() {
        // 服务器1连接元素
        this.server1 = {
            host: document.getElementById('server1-host'),
            username: document.getElementById('server1-username'),
            password: document.getElementById('server1-password'),
            port: document.getElementById('server1-port'),
            connectBtn: document.getElementById('server1-connect-btn'),
            disconnectBtn: document.getElementById('server1-disconnect-btn'),
            infoBtn: document.getElementById('server1-info-btn-action'),
            status: document.getElementById('server1-status'),
            pathInput: document.getElementById('server1-path'),
            filesList: document.getElementById('server1-files'),
            refreshBtn: document.getElementById('server1-refresh'),
            navigateBtn: document.getElementById('server1-navigate'),
            badge: document.getElementById('server1-badge')
        };

        // 服务器2连接元素
        this.server2 = {
            host: document.getElementById('server2-host'),
            username: document.getElementById('server2-username'),
            password: document.getElementById('server2-password'),
            port: document.getElementById('server2-port'),
            connectBtn: document.getElementById('server2-connect-btn'),
            disconnectBtn: document.getElementById('server2-disconnect-btn'),
            infoBtn: document.getElementById('server2-info-btn-action'),
            status: document.getElementById('server2-status'),
            pathInput: document.getElementById('server2-path'),
            filesList: document.getElementById('server2-files'),
            refreshBtn: document.getElementById('server2-refresh'),
            navigateBtn: document.getElementById('server2-navigate'),
            badge: document.getElementById('server2-badge')
        };

        // 其他元素
        this.serverList = document.getElementById('server-list');
        
        // 面板状态元素
        this.server1.statusPanel = document.getElementById('server1-status-panel');
        this.server1.statusText = document.getElementById('server1-status-text');
        this.server1.transferProgress = document.getElementById('server1-transfer-progress');
        this.server1.progressFill = document.getElementById('server1-progress-fill');
        this.server1.transferText = document.getElementById('server1-transfer-text');
        
        this.server2.statusPanel = document.getElementById('server2-status-panel');
        this.server2.statusText = document.getElementById('server2-status-text');
        this.server2.transferProgress = document.getElementById('server2-transfer-progress');
        this.server2.progressFill = document.getElementById('server2-progress-fill');
        this.server2.transferText = document.getElementById('server2-transfer-text');

        this.selectedFiles.set('server1', new Set());
        this.selectedFiles.set('server2', new Set());
    }

    bindEvents() {
        // 服务器1事件
        this.server1.connectBtn.addEventListener('click', () => this.connect('server1'));
        this.server1.disconnectBtn.addEventListener('click', () => this.disconnect('server1'));
        this.server1.refreshBtn.addEventListener('click', () => this.loadFiles('server1'));
        this.server1.navigateBtn.addEventListener('click', () => this.navigateToPath('server1'));
        this.server1.infoBtn.addEventListener('click', () => this.showServerInfo('server1'));

        // 服务器2事件
        this.server2.connectBtn.addEventListener('click', () => this.connect('server2'));
        this.server2.disconnectBtn.addEventListener('click', () => this.disconnect('server2'));
        this.server2.refreshBtn.addEventListener('click', () => this.loadFiles('server2'));
        this.server2.navigateBtn.addEventListener('click', () => this.navigateToPath('server2'));
        this.server2.infoBtn.addEventListener('click', () => this.showServerInfo('server2'));

        // 键盘事件
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                const focusedElement = document.activeElement;
                if (focusedElement.id.startsWith('server1-')) {
                    this.connect('server1');
                } else if (focusedElement.id.startsWith('server2-')) {
                    this.connect('server2');
                }
            }
        });

        // 拖拽事件
        this.setupDragAndDrop();
    }

    async connect(serverId) {
        const server = this[serverId];
        const config = {
            host: server.host.value.trim(),
            username: server.username.value.trim(),
            password: server.password.value,
            port: parseInt(server.port.value) || 22
        };

        if (!config.host || !config.username || !config.password) {
            this.showPanelStatus(serverId, '请填写完整的连接信息', 'error');
            return;
        }

        this.showPanelStatus(serverId, '正在连接...', 'info');
        server.connectBtn.disabled = true;

        try {
            const result = await ipcRenderer.invoke('ssh-connect', config, serverId);
            
            if (result.success) {
                if (serverId === 'server1') {
                    this.server1Connection = result.connectionId;
                } else {
                    this.server2Connection = result.connectionId;
                }

                // 更新UI状态
                server.status.textContent = `已连接: ${config.username}@${config.host}`;
                server.status.className = 'connection-status status-connected';
                server.connectBtn.classList.add('hidden');
                server.disconnectBtn.classList.remove('hidden');
                server.infoBtn.classList.remove('hidden');
                server.refreshBtn.classList.remove('hidden');
                server.navigateBtn.classList.remove('hidden');
                server.badge.textContent = `${config.username}@${config.host}`;
                server.badge.classList.remove('hidden');

                this.showPanelStatus(serverId, '连接成功', 'success');
                await this.loadFiles(serverId);
                this.updateServerList();
            } else {
                this.showPanelStatus(serverId, `连接失败: ${result.error}`, 'error');
            }
        } catch (error) {
            this.showPanelStatus(serverId, `连接异常: ${error.message}`, 'error');
        } finally {
            server.connectBtn.disabled = false;
        }
    }

    async disconnect(serverId) {
        const connectionId = serverId === 'server1' ? this.server1Connection : this.server2Connection;
        const server = this[serverId];

        if (connectionId) {
            await ipcRenderer.invoke('ssh-disconnect', connectionId);
            if (serverId === 'server1') {
                this.server1Connection = null;
            } else {
                this.server2Connection = null;
            }
        }

        // 更新UI状态
        server.status.textContent = '未连接';
        server.status.className = 'connection-status status-disconnected';
        server.connectBtn.classList.remove('hidden');
        server.disconnectBtn.classList.add('hidden');
        server.infoBtn.classList.add('hidden');
        server.refreshBtn.classList.add('hidden');
        server.navigateBtn.classList.add('hidden');
        server.badge.classList.add('hidden');

        server.filesList.innerHTML = `
            <div class="loading">
                <div class="spinner"></div>
                <span>请先连接${serverId}</span>
            </div>
        `;

        this.showPanelStatus(serverId, '已断开连接', 'info');
        this.updateServerList();
    }

    async loadFiles(serverId) {
        const connectionId = serverId === 'server1' ? this.server1Connection : this.server2Connection;
        const server = this[serverId];
        const currentPath = serverId === 'server1' ? this.server1Path : this.server2Path;

        if (!connectionId) return;

        server.filesList.innerHTML = '<div class="loading"><div class="spinner"></div><span>加载中...</span></div>';

        try {
            const result = await ipcRenderer.invoke('ssh-list-files', connectionId, currentPath);
            
            if (result.success) {
                this.renderFileList(result.files, server.filesList, serverId);
                server.pathInput.value = currentPath;
            } else {
                server.filesList.innerHTML = `<div class="error-message">加载失败: ${result.error}</div>`;
            }
        } catch (error) {
            server.filesList.innerHTML = `<div class="error-message">加载异常: ${error.message}</div>`;
        }
    }

    renderFileList(files, container, serverId) {
        const currentPath = serverId === 'server1' ? this.server1Path : this.server2Path;
        
        // 添加上级目录项
        let html = '';
        if (currentPath !== '/') {
            html += this.createFileItemHTML({
                name: '..',
                isDirectory: true,
                size: '',
                date: '',
                isParent: true
            }, serverId);
        }

        // 如果目录为空但不是根目录，显示上级目录选项和提示信息
        if (files.length === 0) {
            if (currentPath !== '/') {
                html += '<div class="loading"><span>目录为空</span></div>';
                container.innerHTML = html;
                this.bindFileEvents(container, serverId);
            } else {
                container.innerHTML = '<div class="loading"><span>目录为空</span></div>';
            }
            return;
        }

        // 先显示目录，再显示文件
        const directories = files.filter(f => f.isDirectory).sort((a, b) => a.name.localeCompare(b.name));
        const regularFiles = files.filter(f => !f.isDirectory).sort((a, b) => a.name.localeCompare(b.name));

        [...directories, ...regularFiles].forEach(file => {
            html += this.createFileItemHTML(file, serverId);
        });

        container.innerHTML = html;
        this.bindFileEvents(container, serverId);
    }

    createFileItemHTML(file, serverId) {
        const icon = file.isParent ? '⬆️' : (file.isDirectory ? '📁' : '📄');
        const size = file.isDirectory || file.isParent ? '' : this.formatFileSize(file.size);
        
        return `
            <div class="file-item" data-name="${file.name}" data-is-directory="${file.isDirectory}" data-server-id="${serverId}">
                <div class="file-icon">${icon}</div>
                <div class="file-name">${file.name}</div>
                <div class="file-size">${size}</div>
                <div class="file-date">${file.date}</div>
            </div>
        `;
    }

    bindFileEvents(container, serverId) {
        const fileItems = container.querySelectorAll('.file-item');
        
        fileItems.forEach(item => {
            const fileName = item.dataset.name;
            const isDirectory = item.dataset.isDirectory === 'true';
            
            // 双击事件 - 进入目录
            item.addEventListener('dblclick', async () => {
                if (isDirectory) {
                    await this.navigateToDirectory(fileName, serverId);
                }
            });

            // 拖拽事件
            if (!isDirectory && fileName !== '..') {
                item.draggable = true;
                item.addEventListener('dragstart', (e) => {
                    item.classList.add('dragging');
                    const currentPath = serverId === 'server1' ? this.server1Path : this.server2Path;
                    const filePath = currentPath.endsWith('/') ? currentPath + fileName : currentPath + '/' + fileName;
                    
                    e.dataTransfer.setData('text/plain', JSON.stringify({
                        fileName,
                        sourceServerId: serverId,
                        filePath
                    }));
                });

                item.addEventListener('dragend', () => {
                    item.classList.remove('dragging');
                });
            }
        });
    }

    async navigateToDirectory(dirName, serverId) {
        if (serverId === 'server1') {
            if (dirName === '..') {
                this.server1Path = this.server1Path.split('/').slice(0, -1).join('/') || '/';
            } else {
                this.server1Path = this.server1Path.endsWith('/') ? this.server1Path + dirName : this.server1Path + '/' + dirName;
            }
        } else {
            if (dirName === '..') {
                this.server2Path = this.server2Path.split('/').slice(0, -1).join('/') || '/';
            } else {
                this.server2Path = this.server2Path.endsWith('/') ? this.server2Path + dirName : this.server2Path + '/' + dirName;
            }
        }
        
        await this.loadFiles(serverId);
    }

    async navigateToPath(serverId) {
        const server = this[serverId];
        const newPath = server.pathInput.value.trim();
        
        if (newPath) {
            if (serverId === 'server1') {
                this.server1Path = newPath;
            } else {
                this.server2Path = newPath;
            }
            await this.loadFiles(serverId);
        }
    }

    setupDragAndDrop() {
        // 为两个文件面板设置拖放区域
        [this.server1.filesList, this.server2.filesList].forEach((panel, index) => {
            const targetServerId = index === 0 ? 'server1' : 'server2';
            
            panel.addEventListener('dragover', (e) => {
                e.preventDefault();
                panel.classList.add('drop-zone');
            });

            panel.addEventListener('dragleave', (e) => {
                if (!panel.contains(e.relatedTarget)) {
                    panel.classList.remove('drop-zone');
                }
            });

            panel.addEventListener('drop', async (e) => {
                e.preventDefault();
                panel.classList.remove('drop-zone');
                
                try {
                    const data = JSON.parse(e.dataTransfer.getData('text/plain'));
                    
                    if (data.sourceServerId !== targetServerId) {
                        await this.transferFileBetweenServers(data, targetServerId);
                    }
                } catch (error) {
                    this.showPanelStatus(targetServerId, '文件传输失败: ' + error.message, 'error');
                }
            });
        });
    }

    async transferFileBetweenServers(fileData, targetServerId) {
        const sourceConnectionId = fileData.sourceServerId === 'server1' ? this.server1Connection : this.server2Connection;
        const targetConnectionId = targetServerId === 'server1' ? this.server1Connection : this.server2Connection;

        if (!sourceConnectionId || !targetConnectionId) {
            this.showPanelStatus(targetServerId, '请确保两台服务器都已连接', 'error');
            return;
        }

        const targetPath = targetServerId === 'server1' ? this.server1Path : this.server2Path;
        const targetFilePath = targetPath.endsWith('/') ? targetPath + fileData.fileName : targetPath + '/' + fileData.fileName;

        this.showTransferProgress(targetServerId, true, `正在传输: ${fileData.fileName}`);

        try {
            const result = await ipcRenderer.invoke('transfer-between-servers', 
                sourceConnectionId, 
                targetConnectionId, 
                fileData.filePath, 
                targetFilePath, 
                fileData.fileName
            );
            
            if (result.success) {
                this.showPanelStatus(targetServerId, `文件传输成功: ${fileData.fileName}`, 'success');
                await this.loadFiles(targetServerId);
            } else {
                this.showPanelStatus(targetServerId, `传输失败: ${result.error}`, 'error');
            }
        } catch (error) {
            this.showPanelStatus(targetServerId, `传输异常: ${error.message}`, 'error');
        } finally {
            this.showTransferProgress(targetServerId, false);
        }
    }

    async showServerInfo(serverId) {
        const connectionId = serverId === 'server1' ? this.server1Connection : this.server2Connection;
        
        if (!connectionId) return;

        try {
            const result = await ipcRenderer.invoke('get-server-info', connectionId);
            if (result.success) {
                alert(`${serverId} 服务器信息:\n\n${result.info}`);
            }
        } catch (error) {
            this.showPanelStatus(serverId, '获取服务器信息失败: ' + error.message, 'error');
        }
    }

    async updateServerList() {
        try {
            const result = await ipcRenderer.invoke('get-active-connections');
            if (result.success) {
                const connections = result.connections;
                if (connections.length === 0) {
                    this.serverList.innerHTML = '<span>未连接任何服务器</span>';
                } else {
                    // 去重处理，避免重复显示相同的连接
                    const uniqueConnections = connections.filter((conn, index, self) => 
                        index === self.findIndex(c => c.panelId === conn.panelId)
                    );
                    const serverInfos = uniqueConnections.map(conn => 
                        `<div class="server-info">${conn.panelId}: ${conn.username}@${conn.host}</div>`
                    ).join('');
                    this.serverList.innerHTML = serverInfos;
                }
            }
        } catch (error) {
            console.error('更新服务器列表失败:', error);
        }
    }

    showTransferProgress(serverId, show, text = '') {
        const server = this[serverId];
        
        if (show) {
            server.transferProgress.classList.remove('hidden');
            server.transferText.textContent = text;
            server.statusText.style.display = 'none';
            
            // 模拟进度条动画
            let progress = 0;
            const interval = setInterval(() => {
                progress += 10;
                server.progressFill.style.width = progress + '%';
                if (progress >= 100) {
                    clearInterval(interval);
                }
            }, 100);
        } else {
            server.transferProgress.classList.add('hidden');
            server.progressFill.style.width = '0%';
            server.statusText.style.display = 'block';
        }
    }

    formatFileSize(bytes) {
        if (!bytes || bytes === '0') return '0 B';
        
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(parseInt(bytes)) / Math.log(1024));
        return Math.round((parseInt(bytes) / Math.pow(1024, i)) * 100) / 100 + ' ' + sizes[i];
    }

    showPanelStatus(serverId, message, type = 'info') {
        const server = this[serverId];
        server.statusText.textContent = message;
        
        // 移除之前的状态类
        server.statusText.className = '';
        
        // 添加新的状态类样式
        if (type === 'error') {
            server.statusText.style.color = '#dc3545';
        } else if (type === 'success') {
            server.statusText.style.color = '#28a745';
        } else {
            server.statusText.style.color = '#17a2b8';
        }

        // 3秒后恢复默认状态
        setTimeout(() => {
            server.statusText.style.color = '#6c757d';
        }, 3000);
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new ServerToServerTransferApp();
}); 